package com.yl.androidutilscenter.http.gson

import com.google.gson.Gson
import com.google.gson.TypeAdapter
import com.google.gson.reflect.TypeToken
import okhttp3.RequestBody
import okhttp3.ResponseBody
import retrofit2.Converter
import retrofit2.Retrofit
import java.lang.reflect.Type


/**
 * @author
 * @description:
 * @date :2024/4/3
 * @version 1.0.0
 */
class MyGsonConverterFactory : Converter.Factory {
    private lateinit var gson:Gson
    private constructor( gson: Gson) : super(){
        this.gson = gson
    }

    companion object {
        fun create(): MyGsonConverterFactory {
            return create(Gson())
        }

        fun create(gson: Gson): MyGsonConverterFactory {
            return MyGsonConverterFactory(gson)
        }
    }

    override fun responseBodyConverter(
        type: Type,
        annotations: Array<out Annotation>,
        retrofit: Retrofit
    ): Converter<ResponseBody, *> {
        val adapter: TypeAdapter<*> = gson.getAdapter(TypeToken.get(type))
        return MyGsonResponseBodyConverter(gson, adapter)
    }

    override fun requestBodyConverter(
        type: Type,
        parameterAnnotations: Array<out Annotation>,
        methodAnnotations: Array<out Annotation>,
        retrofit: Retrofit
    ): Converter<*, RequestBody> {
        val adapter: TypeAdapter<*> = gson.getAdapter(TypeToken.get(type))
        return MyGsonRequestBodyConverter(gson, adapter)
    }

}